<?php

class Favorite_model extends CI_Model
{

    public function favoriteCategory()
    {
        return $this->db->select('id,name')->where(['show' => 1])
            ->limit(100)->get('1_favorite_category')->result_array();
    }

    // 藏品列表
    public function favoriteList($select = '*', $page, $pageSize, $param = [])
    {
        if ($param['ids']) {
            $this->db->where_in('id', $param['ids']);
        }
        // 首页推荐
        if ($param['recommend']) {
            $this->db->where('recommend', 1);
        }
        if ((int)$param['cid']) {
            $this->db->where('catid', (int)$param['cid']);
        }
        // 查询$param['creator'] 作品
        if ($param['creator']) {
            $this->db->where('creator', $param['creator']);
        }
        return $this->db->select($select)->where(['status' => 9])
            ->limit($pageSize, ($page - 1) * $pageSize)
            ->order_by('id desc')
            ->get('1_favorite')->result_array();
    }

    // 藏品详情
    public function favoriteInfo($id, $select = "*")
    {
        $favoriteSQL = $this->db->select($select)
            ->where(['id' => $id, 'status' => 9])->limit(1)->get_compiled_select('1_favorite');
        return $this->db->query($favoriteSQL . ' for update')->row_array();
    }

    // 藏品转义
    public function favoriteTransfer($item = [], $type = false)
    {
        if ($item['thumb']) {
            $item['thumb_id'] = $item['thumb'];
            $item['thumb'] = dr_thumb($item['thumb'], 550, 350);
        }
        if ($item['creator']) {
            $create = $this->models('issuer')->issuerInfo($item['creator']);
            $item['creator_info'] = $this->models('issuer')->issuerTransfer($create);
        }
        if ($item['time']) {
            $item['time'] = date('Y-m-d H:i', $item['time']);
        }
        if ($item['start_time']) {
            $item['start_time'] = $item['start_time'] > time() ? $item['start_time'] - time() : 0;
        }
        if ($item['type']) {
            $item['type'] = $item['type'] == 'buy' ? '藏品' : '盲盒';
        }
        if ($item['catid']) {
            $item['catid_name'] = dr_cat_value('favorite', $item['catid'], 'name');
        }
        if ($item['status'] && $type) {
            switch ($type) {
                case 'my':
                    ### 购买的藏品状态
                    $item['status_msg'] = $item['status'] == 1 ? '已获得' : '已上架';
                    break;
                default:
                    $item['status_msg'] = '拥有';
                    break;
            }
        }
        return $item;
    }

    // 更新藏品/盲盒的销售件数
    public function upSellNum($id, $mod = '')
    {
        if (empty($id)) {
            return false;
        }
        return $this->db->set('buy_nums', 'buy_nums +1', false)->where('id', $id)->update("1_{$mod}");
    }

    // 收藏状态
    public function collectionStatus($cid, $uid)
    {
        if (empty($cid) || empty($uid)) {
            return false;
        }
        return $this->db->select('id,status')
            ->where(['cid' => $cid, 'uid' => $uid])->limit(1)->get("1_favorite_favorite")->row_array();
    }

    // 更新收藏
    public function upCollection($id, $data)
    {
        if (empty($data) or empty($id)) {
            return false;
        }
        return $this->db->where(['id' => $id])->set($data)->update("1_favorite_favorite");
    }

    // 加入收藏
    public function addCollection($data)
    {
        if (empty($data)) {
            return false;
        }
        $collectionData = [
            'cid' => $data['cid'],
            'uid' => $data['uid'],
            'title' => $data['title'],
            'status' => 1,
            'inputtime' => time()
        ];
        return $this->db->insert("1_favorite_favorite", $collectionData);
    }

    /**
     * 订单入库
     * @param $data
     * @param string $type
     * @return mixed
     */
    public function addOrder($data, string $type = '')
    {
        if (empty($data) || empty($type)) {
            return false;
        }
        $this->db->insert('1_order', [
            'sn' => $this->createSn(),
            'mid' => $type,
            'buy_uid' => $data['member']['uid'],
            'buy_username' => $data['member']['username'],
            'sell_uid' => $data['info']['uid'],
            'sell_username' => $data['info']['author'],
            'creator_id' => $type == 'favorite' ? $data['info']['creator'] : 0,
            'order_time' => time(),
            'order_status' => 1,
            'order_price' => $data['info']['price'],
            'pay_type' => '',
            'pay_id' => 0,
            'pay_status' => 0,
            'pay_time' => 0,
            'team_code' => $data['team_code'] ?: ''
        ]);
        return $this->db->insert_id();
    }

    /**
     * 入库订单商品表
     * @param $oid
     * @param $data
     * @return mixed
     */
    public function addOrderGood($oid, $data)
    {
        return $this->db->insert('1_order_goods', [
            'oid' => $oid,
            'cid' => $data['info']['id'],
            'title' => $data['info']['title'],
            'catid' => $data['info']['catid'],
            'thumb' => $data['info']['thumb'],
            'sn' => $data['nums'],
            'total' => $data['info']['nums'],
            'order_price' => $data['info']['price']
        ]);
    }

    // 生成流水订单号
    protected static function createSn(): string
    {
        return date('Ymd') .
            substr(implode(null, array_map('ord', str_split(substr(uniqid(), 7, 13), 1))), 0, 8);
    }

    //订单详情
    public function orderInfo($oid, $select = '*')
    {
        return $this->db->select($select)->where(['id' => $oid])->limit(1)->get('1_order')->row_array();
    }

    // 订单详情和订单商品信息
    public function orderAndGood($oid, $select = "*", $param = [])
    {
        if (empty($oid)) {
            return null;
        }
        return $this->db->select($select)
            ->from('1_order as a')
            ->join('1_order_goods as b', 'a.id=b.oid', 'left')
            ->where(['a.id' => $oid])->limit(1)->get()->row_array();
    }

    // 订单商品表
    public function goodsList($id)
    {
        return $this->db->select('oid,cid,title,thumb')
            ->{is_array($id) ? 'where_in' : 'where'}('oid', $id)->get('1_order_goods')->result_array();
    }

    // 盲盒订单列表
    public function boxOrderList($condition, $page, $pageSize)
    {
        if (!is_array($condition)) {
            return null;
        }
        return $this->db->select('id,sn,order_time,order_status,order_price,pay_status,pay_id')
            ->where($condition)
            ->limit($pageSize, ($page - 1) * $pageSize)->order_by('order_status asc,id desc')
            ->get('1_order')->result_array();
    }

    //操作订单
    public function operateOrder(int $id, $operate = [])
    {
        if (empty($id) || empty($operate)) {
            return false;
        }
        return $this->db->set($operate)->where("id", $id)->update("1_order");
    }

    // 订单转义
    public function orderTransfer($item)
    {
        if ($item['order_time']) {
            $item['order_time'] = date('Y-m-d H:i', $item['order_time']);
        }
        $item['all_status'] = $item['order_status'] + $item['pay_status'];
        return $item;
    }

    /**
     * 成功购买之后执行此方法 , 获得卡片 , 且处于可交易状态
     * @param $order
     * @return mixed
     */
    public function gainCard($order)
    {
        return $this->db->insert('1_favorite_my', [
            'uid' => $order['buy_uid'],
            'oid' => $order['id'],
            'cid' => $order['cid'],
            'catid' => $order['catid'],
            'title' => $order['title'],
            'number' => $order['sn'],
            'total' => $order['total'],
            'thumb' => $order['thumb'],
            'price' => $order['order_price'],
            'time' => time(),
            'ip' => $_SERVER['REMOTE_ADDR'],
            'status' => 1,
            'type' => $order['type']
        ]);
    }


    // 获取购买的藏品详情
    public function cardInfo($condition, $select = '*')
    {
        if (!is_array($condition)) {
            return null;
        }
        $keys = array_keys($condition);
        foreach ($keys as $key) {
            if (!in_array($key, ['id', 'oid', 'uid'])) {
                return null;
            }
        }
        $cardSQL = $this->db->select($select)->where($condition)->limit(1)->get_compiled_select('1_favorite_my');
        return $this->db->query($cardSQL . ' for update')->row_array();
    }

    // 获取附表信息
    public function getContent($id)
    {
        return $this->db->select('content,treaty,mark,standard,network')
            ->where('id', $id)->limit(1)->get('1_favorite_data_0')->row_array();
    }

    // 更新自己购买的藏品信息
    public function operateCard($id, $status)
    {
        if (empty($id) || empty($status)) {
            return false;
        }
        return $this->db->set('status', $status)->where('id', $id)->update('1_favorite_my');
    }

    // 购买的藏品和开盲盒获得物品的列表
    public function buyList($param = [], $page, $pageSize)
    {
        if (!is_array($param)) {
            return null;
        }
        if (isset($param['type'])) {
            $this->db->{is_array($param['type']) ? 'where_in' : 'where'}('status', $param['type']);
        }
        return $this->db->select('id,uid,cid,catid,title,number,total,thumb,price,time,status')
            ->where('uid', $param['uid'])
            ->order_by('id desc,status desc')
            ->limit($pageSize, ($page - 1) * $pageSize)
            ->get('1_favorite_my')->result_array();
    }

    // 更新锁状态
    public function operateLock($id, $value)
    {
        if (empty($id)) {
            return false;
        }
        return $this->db->set('lock', $value)->where('id', $id)->update('1_favorite');
    }

    /**
     * @param $oid // 订单id
     * @param $type // 订单类型
     * @param $cid // 管理商品id
     * @param  $sn // 订单编号
     * @return false
     */
    public function addQueue($uid, $oid, $type, $cid, $sn = '')
    {
        if (empty($oid) || empty($uid)) {
            return false;
        }
        return $this->db->insert('1_order_queue', [
            'oid' => $oid,
            'uid' => $uid,
            'cid' => $cid,
            'sn' => $sn ?: 0,
            'type' => $type,
            'time' => time(),
            'end_time' => time() + 300,
            'status' => 0
        ]);
    }

    // 删除队列订单
    public function delQueue($oid)
    {
        return $this->db->where('oid', $oid)->delete('1_order_queue');
    }

    // 删除时间内的队列
    public function delOverQueue($times)
    {
        return $this->db->where(['end_time <' => $times, 'status' => 1])->delete('1_order_queue');
    }

    //获取时间范围内的最大订单时间和数量
    public function maxTimeAndNum($uid, $times): array
    {
        if (empty($uid) || empty($times)) {
            return ['end' => 0, 'total' => 0];
        }
        return $this->db->select("IFNULL(max(end_time),0) as end ,count(id) as total")
            ->where(['uid' => $uid, 'end_time >' => $times])->get('1_order_queue')->row_array();
    }


    // 获取队列时间
    public function getQueue($oid)
    {
        return $this->db->select('oid,cid,end_time')->where('oid', $oid)->limit(1)->get('1_order_queue')->row_array();
    }

    // 更新队列信息
    public function upQueue($id)
    {
        return $this->db->set('status', 1)->where('id', $id)->update('1_order_queue');
    }

    // 获取订单索状态
    public function snLockStatus($cid, $sn)
    {
        return $this->db->select('time')->where(['cid' => $cid, 'type' => 'favorite', 'sn' => $sn])
            ->limit(1)->get('1_order_queue')->row_array();
    }

    // 获取此藏品上锁的编号
    public function getLockSn($cid)
    {
        return $this->db->select("sn")->where(['cid' => $cid])->get('1_order_queue')->result_array();
    }

    // 将盲盒获得的物品入库
    public function boxGoods($data)
    {
        return $this->db->insert('1_order_box', [
            'oid' => $data['oid'],
            'cid' => $data['cid'],
            'title' => $data['title'],
            'catid' => $data['catid'],
            'thumb' => $data['thumb'],
            'sn' => $data['buy_id'],
            'total' => $data['total'],
            'order_price' => $data['price']
        ]);
    }

    // 取出此商品的已购编号结果
    public function getSn($cid)
    {
        return $this->db->select('sn')->where('cid', $cid)->limit(1)->get('1_favorite_sn')->row()->sn;
    }
}